//
//  JZHPersonaldetailsViewController.m
//  极致荟
//
//  Created by hetao on 14-5-7.
//  Copyright (c) 2014年 mac. All rights reserved.
//

#import "JZHPersonaldetailsViewController.h"
#import "JZHPothTableViewCell.h"
#import "JZHMessgeViewController.h"
#import "JZHTheDiary.h"
#import "JZHPusMessgeViewController.h"

#import "JZHPhotoCell.h"
#import "JZHSelectPhotoView.h"

@interface JZHPersonaldetailsViewController ()
{
    NSMutableArray *dataArrayKey;
    NSMutableDictionary *dataDict;
    JZHSelectPhotoView *selectPhotoView;
    
    //图片放大使用的视图
    UIScrollView *fullScreenView;
}
@end

@implementation JZHPersonaldetailsViewController
NSString *str;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}


+ (JZHPersonaldetailsViewController *)shareName:(User *)user
{
    JZHPersonaldetailsViewController *viewcontroller=[[JZHPersonaldetailsViewController alloc]init];
    viewcontroller.user=user;
    viewcontroller.navigationItem.title = viewcontroller.user.name;
   
    return viewcontroller;
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    
    dataArrayKey=[[NSMutableArray alloc]init];
    dataDict = [NSMutableDictionary dictionary];
    [self httpLoad];
    self.tableView.tableHeaderView = self.headerView;
    
    //设置左侧按钮
    UIButton *leftButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 12, 20)];
    [leftButton addTarget:self action:@selector(leftDrawerButtonPress:) forControlEvents:UIControlEventTouchUpInside];
    [leftButton setImage:[UIImage imageNamed:@"返回"] forState:UIControlStateNormal];
    UIBarButtonItem *leftBarButton = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
    self.navigationItem.leftBarButtonItem = leftBarButton;
    [self.headImage.layer setBorderWidth:2];
    [self.headImage.layer setBorderColor:[[UIColor whiteColor] CGColor]];
    [self.headImage.layer setCornerRadius:8];
    [self.headImage.layer setMasksToBounds:YES];
    [ImageCache imageUrl:self.user.userHeadImage UiImageview:self.headImage];
    self.name.text=self.user.name;
    if(OSVersionIsAtLeastiOS7>=7.0)
    {
        self.automaticallyAdjustsScrollViewInsets=NO;
    }
    //设置右侧导航按钮
    UIButton *rightButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 25, 5)];
    [rightButton addTarget:self action:@selector(rightDrawerButtonPress:) forControlEvents:UIControlEventTouchUpInside];
   
   

    if(self.user.userId==[User defuceUser].userId)
    {
        [rightButton setImage:[UIImage imageNamed:@"详细资料圈圈"] forState:UIControlStateNormal];
    }else
    {
        [rightButton setFrame:CGRectMake(0, 0, 50, 10)];
        [rightButton setTitle:@"关注" forState:UIControlStateNormal];
        [rightButton setTitleColor:TEXTBULE forState:UIControlStateNormal];
    }
    UIBarButtonItem *rightBarButton = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
    self.navigationItem.rightBarButtonItem = rightBarButton;
    [self vipiconimage];
}

//会员图标显示设置
- (void)vipiconimage
{
    int vip=self.user.vip;
    if(vip==0)
    {
        if(self.user.sex==1)
        {
            self.vipicon.image=[UIImage imageNamed:@"no1-1"];
        }else
        {
            self.vipicon.image=[UIImage imageNamed:@"no0-1"];
        }
        
        return;
    }
    
    if(vip==1)
    {
        self.vipicon.image=[UIImage imageNamed:@"vip1-1"];
    }else
    {
        self.vipicon.image=[UIImage imageNamed:@"vip2-1"];
    }
}

- (void)rightDrawerButtonPress:(UIButton *)but
{
    if(self.user.userId==[User defuceUser].userId)
    {
        JZHMessgeViewController *messageVC = [[JZHMessgeViewController alloc]init];
        [messageVC setStrUserID:[NSString stringWithFormat:@"%d", self.user.userId]];
        [self.navigationController pushViewController:messageVC animated:YES];
    }else
    {
        [self guanLoadHttp];
    }
    
}

- (void)guanLoadHttp
{
    NSDictionary *dic=[[NSDictionary alloc]initWithObjectsAndKeys:[NSNumber numberWithInt:self.user.userId],@"attentionId",[NSNumber numberWithInt:[User defuceUser].userId],@"userId", nil];
    [HttpRequest httpRequestPost:JZHHTTPURL(@"friends/attentionFriend") parameters:dic block:^(id data, HttpReturnCode rerurncode) {
        if(rerurncode==0)
        {
            [MMProgressHUD showSuccessWithTips:@"关注成功"];
        }else
        {
            [MMProgressHUD showInformationWithTips:@"关注失败"];
        }
    }];
}
#pragma mark-------TableView代理----------
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section;

{
    return dataArrayKey.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];
    return cell.frame.size.height;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *pengyoucell=@"photoCell";
    
    JZHPhotoCell *cell = [tableView dequeueReusableHeaderFooterViewWithIdentifier:pengyoucell];
    
    if (nil == cell)
    {
        cell = [[JZHPhotoCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:pengyoucell];
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    }
    
    float height = 0;
    
    if([self.userID isEqualToString:[NSString stringWithFormat:@"%d",[User defuceUser].userId]])   //当是自己的ID时显示添加动态的相机
    {
        //当为0的时候要加个照相的按钮
        if (indexPath.row == 0)
        {
            height = [cell setFirstCellData:[dataDict objectForKey:[dataArrayKey objectAtIndex:0]]];
            [cell setDelegate:self];
        }
        else
        {
            NSMutableDictionary *dict = [NSMutableDictionary dictionary];
            [dict setValue:[dataDict objectForKey:[dataArrayKey objectAtIndex:indexPath.row]] forKey:@"data"];
            [dict setValue:[dataArrayKey objectAtIndex:indexPath.row] forKey:@"time"];
            
            height = [cell setCellData:dict];
            [cell setDelegate:self];
        }
    }
    else            //当是别人时不显示
    {
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        [dict setValue:[dataDict objectForKey:[dataArrayKey objectAtIndex:indexPath.row]] forKey:@"data"];
        [dict setValue:[dataArrayKey objectAtIndex:indexPath.row] forKey:@"time"];
        
        height = [cell setCellData:dict];
        [cell setDelegate:self];
    }
    
    [cell setFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, height)];
    
    return cell;
    
//    JZHPothTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:pengyoucell];
//   
//    if(!cell)
//    {
//        cell=[[[NSBundle mainBundle] loadNibNamed:@"JZHPothTableViewCell" owner:self options:nil] objectAtIndex:0];
//    }
//     cell.viewcontroller=self;
//    if([User defuceUser].userId==self.user.userId && indexPath.row==0)
//    {
//        cell.poth.hidden=NO;
//        cell.anbut.hidden=YES;
//        cell.conten.hidden=YES;
//         return cell;
//    }
//    
//    if([User defuceUser].userId==self.user.userId && indexPath.row!=0)
//    {
//        [cell addCellData:dataarr[indexPath.row-1]];
//        [cell.anview setFrame:CGRectMake(cell.anbut.frame.origin.x, cell.anbut.frame.origin.y-5, cell.anview.frame.size.width, cell.anview.frame.size.height)];
//        [cell.anview setHidden:YES];
//        [cell addSubview:cell.anview];
//        return cell;
//    }else
//    {
//        [cell addCellData:dataarr[indexPath.row]];
//        [cell.anview setFrame:CGRectMake(cell.anbut.frame.origin.x, cell.anbut.frame.origin.y-5, cell.anview.frame.size.width, cell.anview.frame.size.height)];
//        [cell.anview setHidden:YES];
//        
//        [cell addSubview:cell.anview];
//        return cell;
//
//    }
    
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
//    for( int i=0;i<dataarr.count;i++)
//    {
//       
//        JZHPothTableViewCell *cell=(JZHPothTableViewCell *) [tableView cellForRowAtIndexPath: [NSIndexPath indexPathForRow:i inSection:0]] ;
//        if(cell.anbut.selected)
//        {
//            [cell showzan:cell.anbut];
//        }
//    }
  
   
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)leftDrawerButtonPress:(UIButton *)sender
{
    [UINavigationController Pop:self];
}

#pragma 请求数据
///请求数据
- (void)httpLoad
{
    if (self.userID.length == 0)
    {
        self.userID = [NSString stringWithFormat:@"%d",self.user.userId];
    }
    
  
    
    NSDictionary *dic =[[NSDictionary alloc]initWithObjectsAndKeys:self.userID, @"userId", @"0", @"page",nil];
    
    [HttpRequest httpRequestPost:JZHHTTPURL(@"friendsDynamic/userDynamicList") parameters:dic block:^(id data, HttpReturnCode rerurncode) {
        
        if(rerurncode==0)
        {
            [MMProgressHUD dismiss];
            NSLog(@"%@",data);
            //头像的域名
            NSString *imageHead = [[data objectForKey:@"data"] objectForKey:@"imgPrefix"];
            
            self.navigationItem.title=[[[data objectForKey:@"data"] objectForKey:@"userInfo"] objectForKey:@"userName"];
          
            //数据
            NSArray *arrayData = [[data objectForKey:@"data"] objectForKey:@"list"];
            
            NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];  //记录数据
            
            if(self.user.userId == [User defuceUser].userId)
            {
                NSString *now = [NSString stringWithFormat:@"%@",[NSDate date]];
                NSString *dayAndMonthNow = [now substringWithRange:NSMakeRange(5, 5)];
                [dataArrayKey addObject:dayAndMonthNow];
                [dictionary setValue:[NSMutableArray array] forKey:dayAndMonthNow];
            }

            
            for (NSDictionary *item in arrayData)
            {
                NSDate *date = [NSDate dateWithTimeIntervalSince1970:[[item objectForKey:@"addTime"] longLongValue]];
                NSString *strDate = [NSString stringWithFormat:@"%@", date];
                NSString *dayAndMonth = [strDate substringWithRange:NSMakeRange(5, 5)];
                
                if ([[dictionary allKeys] containsObject:dayAndMonth])
                {
                    NSMutableArray *arr = [dictionary objectForKey:dayAndMonth];
                    [arr addObject:item];
                    [dictionary setValue:arr forKey:dayAndMonth];
                }
                else
                {
                    NSMutableArray *arr = [NSMutableArray array];
                    [arr addObject:item];
                    [dictionary setValue:arr forKey:dayAndMonth];
                    
                    [dataArrayKey addObject:dayAndMonth];
                }
            }
            
            NSDictionary *dict = [[data objectForKey:@"data"]objectForKey:@"userInfo"];
            NSString *strCompany;
            if([dict objectForKey:@"company"]==[NSNull null])
            {
                strCompany=@"";
            }else
            {
                strCompany = [dict objectForKey:@"company"];
                
            }
            self.gs.text=strCompany;
            
            for (NSString *strKey in dictionary.allKeys)
            {
                NSArray *array = [dictionary objectForKey:strKey];
                
                NSMutableArray *arrayDiary = [NSMutableArray array];
                for(NSDictionary *datadic in array)
                {
                    JZHTheDiary *td=[[JZHTheDiary alloc]init];
                    td.tdid=[datadic objectForKey:@"id"];
                    td.content=[datadic objectForKey:@"content"];
                    
                    //设置图片地址
                    id fdImage = [datadic objectForKey:@"fdImage"];
                    NSDictionary *dict = [fdImage isKindOfClass:[NSDictionary class]]?fdImage:[NSDictionary dictionary];
                    NSMutableArray *array = [NSMutableArray array];
                    for (NSString *strKey in dict.allKeys)
                    {
                        NSString *strName = [dict objectForKey:strKey];
                        NSString *strURL = [NSString stringWithFormat:@"%@%@",imageHead, strName];
                        [array addObject:strURL];
                    }
                    td.images = array;
                    
                    td.tdDate=[NSDate dateWithTimeIntervalSince1970:[[datadic objectForKey:@"addTime"] longLongValue]];
                    
                    td.pathHead=[[data objectForKey:@"data"] objectForKey:@"imgPrefix"];
                    [arrayDiary addObject:td];
                }

                [dataDict setValue:arrayDiary forKey:strKey];
            }
            [self.tableView reloadData];
        }else
        {
            [MMProgressHUD showInformationWithTips:@"数据加载失败"];
        }
        
    }];
    
}

#pragma mark - 打开相机和相册视图
///打开相机和相册视图
- (void)openCameraAndAlbum
{
    selectPhotoView = [[JZHSelectPhotoView alloc]initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height)];
    [selectPhotoView setDelegate:self];
    [self.view addSubview:selectPhotoView];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(touchTap:)];
    [selectPhotoView addGestureRecognizer:tap];
}

- (void)touchTap:(UITapGestureRecognizer *)tap
{
    [selectPhotoView removeSubView:^{
        [selectPhotoView removeFromSuperview];
    }];
}

#pragma mark 相册 代理方法实现-------------
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    UIImage *img;
    NSLog(@"%@",info);
    if(picker.sourceType == UIImagePickerControllerSourceTypeCamera){
        img=[info objectForKey:UIImagePickerControllerEditedImage];
    }else {
        img=[info objectForKey:UIImagePickerControllerOriginalImage];
    }
    [self dismissViewControllerAnimated:NO completion:^{
    }];
    [self.navigationController pushViewController:[JZHPusMessgeViewController shareImage:img] animated:YES];
}

#pragma mark-
#pragma mark--图片点击放大
/*
 *图片点击放大
 */
-(void)imageViewBig:(NSArray *)array andIndex:(NSString *)strIndex
{
    int index = [strIndex intValue];
    
    fullScreenView = [[UIScrollView alloc] initWithFrame:self.view.window.frame];
    [fullScreenView setContentSize:CGSizeMake([UIScreen mainScreen].bounds.size.width * array.count, [UIScreen mainScreen].bounds.size.height)];
    [fullScreenView setBackgroundColor:[UIColor blackColor]];
    [fullScreenView setPagingEnabled:YES];
    
    [self.view.window addSubview:fullScreenView];
    [fullScreenView setAlpha:0];
    [UIView animateWithDuration:0.2f animations:^{
        [fullScreenView setAlpha:1];
    } completion:^(BOOL finished) {
        [[UIApplication sharedApplication] setStatusBarHidden:YES];
        for(int i = 0; i < array.count; i++)
        {
            UIImageView *displayImgV = [[UIImageView alloc] initWithFrame:CGRectMake(i * [UIScreen mainScreen].bounds.size.width, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height)];
            [displayImgV setBackgroundColor:[UIColor clearColor]];
            
            [displayImgV setContentMode:UIViewContentModeScaleAspectFit];
            [fullScreenView addSubview:displayImgV];
            
            UIActivityIndicatorView *indicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
            [indicator setCenter:displayImgV.center];
            [displayImgV addSubview:indicator];
            [indicator startAnimating];
            
            [ImageCache imageUrl:[array objectAtIndex:i] UiImageview:displayImgV];
            
            [indicator stopAnimating];
            [indicator removeFromSuperview];
            
        }
        [fullScreenView setContentOffset:CGPointMake([UIScreen mainScreen].bounds.size.width * index, 0) animated:NO];
        UITapGestureRecognizer *lastTouch = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(reduceImage:)];
        [fullScreenView addGestureRecognizer:lastTouch];
    }];
    
}

/*
 *图片缩小回到原位置
 */
- (void)reduceImage:(UITapGestureRecognizer *)aTapGestureRecognizer
{
    [[UIApplication sharedApplication] setStatusBarHidden:NO];
    
    [UIView animateWithDuration:0.2f animations:^{
        [fullScreenView setAlpha:0];
    } completion:^(BOOL finished) {
        
        [fullScreenView removeFromSuperview];
        fullScreenView = nil;
    }];
}

@end
